package com.syj.qdp.framework.web.core.xss;

import com.syj.qdp.framework.web.config.XssProperties;
import com.syj.qdp.framework.common.util.collection.CollectionUtils;
import org.springframework.util.PathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.function.BiPredicate;

/**
 * Xss 请求过滤器
 * @author Lyon
 */
public class XssRequestFilter extends OncePerRequestFilter {

    private XssProperties properties;
    private PathMatcher pathMatcher;

    public XssRequestFilter(XssProperties properties, PathMatcher pathMatcher) {
        this.properties = properties;
        this.pathMatcher = pathMatcher;
    }

    private BiPredicate<String,String> biPredicate = (excludeUri, uri) -> pathMatcher.match(excludeUri,uri);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        chain.doFilter(new XssRequestWrapper(request),response);
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        String uri = request.getRequestURI();
        return !properties.isEnable() || CollectionUtils.anyMatch(properties.getExcludes(),uri,biPredicate);
    }
}
